import { AfterContentChecked, Directive, ElementRef, Input } from '@angular/core';

@Directive({
  selector: '[oyRButtonAuthority]'
})

/**
 * 公司：xxx有限公司
 * 版权：xxx2020
 * 描述：按钮权限控制指令, 控制按钮，超链接，开关组件显示以及文本文字
 * 作者：oyjl
 * 时间：2020-03-05 13:15:34
 */
export class RButtonAuthorityDirective implements AfterContentChecked {

  @Input('oyRButtonAuthority') restUrl: string; // 权限
  @Input() oyLangKey: string; // 多语言转换
  private currentLang; // 获取当前的语言对象
  constructor(public el: ElementRef) {
    this.currentLang = JSON.parse(sessionStorage.getItem('currentLang'));
  }

  ngAfterContentChecked(): void {
    if (this.restUrl) {
      const funcs = JSON.parse(sessionStorage.getItem('currentFuncs')) || [];
      const urlArr = [];
      const nameArr = [];
      funcs.forEach(element => {
        urlArr.push(element.url);
        nameArr.push(element.funcName);
      });
      const index = urlArr.indexOf(this.restUrl);
      if (index < 0) {
        if (this.el.nativeElement.localName === 'p-inputswitch') {
          this.el.nativeElement.innerHTML = `<div role="checkbox" class="ui-inputswitch ui-widget ui-inputswitch-checked
                 ui-state-disabled" ng-reflect-ng-class="[object Object]" aria-checked="true"><div class="ui-helper-hidden-accessible">
                 <input type="checkbox" disabled=""></div><span class="ui-inputswitch-slider"></span></div>`;
        } else {
          this.el.nativeElement.style.display = 'none';
        }
      } else {
        this.el.nativeElement.style.display = 'inline-block';
        if (this.el.nativeElement.localName !== 'p-inputswitch') {
          if (this.el.nativeElement.localName !== 'button') {
            this.el.nativeElement.innerText = this.oyLangKey ? this.currentLang[this.oyLangKey] : nameArr[index];
          } else if (this.el.nativeElement.localName === 'button') {
            if (this.el.nativeElement.children[this.el.nativeElement.children.length - 1]) {
              this.el.nativeElement.children[this.el.nativeElement.children.length - 1].innerText = this.oyLangKey ?
                this.currentLang[this.oyLangKey] : nameArr[index];
            }
          }
        }
      }
    }
  }
}
